package com.wangfei.lecture.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    private ServerSocket serverSocket;
    private int port;

    public SocketServer(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        System.out.println("Starting the socket server at port:" + port);
        serverSocket = new ServerSocket(port);

        System.out.println("Waiting for clients...");
        Socket client = serverSocket.accept();

        try (InputStream is = client.getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
             OutputStream os = client.getOutputStream();
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
             ) {
//            sendWelcomeMessage(bw);
            String content = null;
            while ((content = br.readLine()) != null) {
                if ("exits".equals(content)) {
                    break;
                }
                showIncomeMessage(content);
            }
            sendWelcomeMessage(bw);

        }
    }
    private void showIncomeMessage(String message) {
        System.out.println(message);
    }
    private void sendWelcomeMessage(BufferedWriter writer) throws IOException {
        writer.write("Hello. You are connected to a Simple Socket Server. What is your name?");
        writer.flush();
    }

    /**
     * Creates a SocketServer object and starts the server.
     *
     * @param args
     */
    public static void main(String[] args) {
        // Setting a default port number.
        int portNumber = 9990;

        try {
            // initializing the Socket Server
            SocketServer socketServer = new SocketServer(portNumber);
            socketServer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}